package com.zfc.life.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zfc.life.comm.BaseUserInfo;
import com.zfc.life.utils.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zfc
 * @Date 2024/5/24 13:44
 * @Description JWTInterceptors
 */
@Component
public class JWTInterceptors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if (!request.getRequestURI().contains("backend")) {
            return true;
        }

        String token = request.getHeader("token");
        String queryString = null;
        if (!StringUtils.isEmpty(request.getQueryString())) {
            queryString = request.getQueryString().contains("token=") ? request.getQueryString().split("token=")[1] : "";
        }
        try {
            //根据token解析数据，因为配置了全局异常处理中心，如果有异常会在全局异常中心处理异常
            DecodedJWT tokenInfo = JWTUtils.verify(token == null || token == "" ? queryString : token);
            BaseUserInfo.set("name", tokenInfo.getClaim("name").asString());

            return true;
        } catch (TokenExpiredException | AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg", "token过期");
            response.setStatus(404);
            request.getSession().setAttribute("errorMessage", "token过期，请重新登录！");
            response.sendRedirect("/login");
        } catch (SignatureVerificationException | JWTDecodeException e) {
            e.printStackTrace();
            response.setStatus(404);
            request.getSession().setAttribute("errorMessage", "token无效！");
            response.sendRedirect("/404");
            return false;
        }
        return false;
    }
}
